package engine;

import java.net.*;
import java.security.*;
import java.security.cert.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
import java.io.*;

import javax.net.ssl.*;

import microcontroler.MicroControler;

import tasks.TaskThread;

import com.managment.data.Profile;

import database.DatabaseConnector;

public class HomeService extends Thread{		
	private ServerSocket homeService;
	private ObjectInputStream ois;
	private ObjectOutputStream oos;
	private Socket homeClient;
	private HomeUser newUser;
	private static List <HomeUser> homeUsers;
	private String password;
	private int port;
	private DatabaseConnector dc;
	private MicroControler mc;
	public  List<Profile> profiles;
	private Profile active_profile;
	private List<TaskThread> active_tasks;
	
	public HomeService(){
		dc = new DatabaseConnector();
		mc = new MicroControler();
		try {
		    if(loadConf("home.conf") != 2){
		    	System.out.println("Plik konfiguracyjny serwera jest niepoprawny!");
		    }
			homeService = new ServerSocket(port);
			System.out.println("Stoi HomeService");
		} catch (IOException e) {
			System.out.println("Nie udało się postawić HomeServicu");
			System.exit(1);
		}
		homeUsers = new ArrayList<HomeUser>();
		profiles = dc.getProfils();
		active_tasks = new ArrayList<TaskThread>();
	}
	
	public int loadConf(String file){
		String line;
	    BufferedReader in = null;
	    String[] tmp = null;
	    try {
	    	in = new BufferedReader(new FileReader(file));
	    } catch (FileNotFoundException e) {
	    	System.out.println("Nie ma takiego pliku");
	    	System.exit(1);
	    }
	    System.out.println("Wczytano plik konfiguracyjny: "+file);
	    int n = 0;
	    try {
			while ((line = in.readLine()) != null) {
				tmp = line.split(":");
				password = tmp[0];
				n++;
				port = Integer.valueOf(tmp[1]);
				n++;

				if(n == 2){
					System.out.println("Hasło do serwera: "+password+", port: "+port);
					break;
				}
			}
		} catch (NumberFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return n;
	}
	
	public void run(){
		while(true){
			try {
				homeClient = homeService.accept();
    			System.out.println(Utils.getSysTime()+" -> "+homeClient.getInetAddress()+ "Łączy się");
				oos = new ObjectOutputStream(homeClient.getOutputStream());
				oos.flush();
				ois = new ObjectInputStream(homeClient.getInputStream());
				newUser = new HomeUser(homeClient, homeUsers, ois, oos, password, active_profile, profiles, active_tasks,dc,mc);
				newUser.start();
				homeUsers.add(newUser);
				System.out.println(Utils.getSysTime()+" -> "+homeClient.getInetAddress()+ "Połączył się");
			} catch (IOException e) {
				System.out.println(e+"\n"+Utils.getSysTime()+" -> HomeService padł");
			}
		}
	}
}